package com.base.www.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by wangyang on 2017/7/31.
 */
public class RunTests {
    public static void main(String[] args){
        test2();
    }

    public static void test1(){
        int tests = 0;
        int passed = 0;
        Class testClass = Samlpe.class;
        for(Method m : testClass.getDeclaredMethods()){
            if(m.isAnnotationPresent(TestAnnotation.class)){
                tests++;
                try{
                    m.invoke(null);
                    passed++;
                } catch (InvocationTargetException e) {
                    System.out.println(m + "failed : " + e);
                }catch (Exception e){
                    System.out.println("Invaild @TestAnnotation : " + m);
                }

            }
        }
        System.out.printf("passed : %d , Failed : %d%n", passed, tests-passed);
    }

    public static void test2(){
        int tests = 0;
        int passed = 0;
        Class testClass = Sample2.class;
        for(Method m : testClass.getDeclaredMethods()){
            if(m.isAnnotationPresent(ExceptionTestAnnotation.class)){
                tests++;
                try{
                    m.invoke(null);
                    System.out.printf("Test %s failed : no exception %n", m);
                } catch (InvocationTargetException e) {
                    Throwable exc = e.getCause();
                    Class<? extends Exception> excType = m.getAnnotation(ExceptionTestAnnotation.class).value();
                    if(excType.isInstance(exc)){
                        passed++;
                    }else{
                        System.out.printf("Test %s failed : excepted %s, got %s%n", m, excType.getName(), e.getClass().getName());
                    }
                    System.out.println(m + "failed : " + e);
                }catch (Exception e){
                    System.out.println("Invaild @TestAnnotation : " + m);
                }

            }
        }
        System.out.printf("passed : %d , Failed : %d%n", passed, tests-passed);
    }
}
